package src

import (
	"net/http"
	"time"
	"fmt"
	"os"
	"flag"
	"strings"
	"strconv"
	"events"
)


var (
	wd = flag.String("wd", "/var/www", "工作根目录")
	ip= flag.String("ip", "0.0.0.0", "webhook ip")
	port= flag.Int("port", 9000, "webhook 监听的端口")
	signatureKeyFileName = "signature.key"
)

func init() {
	flag.Usage = usage
}

func usage() {
	fmt.Fprintln(os.Stderr, ` `)
	fmt.Fprintln(os.Stderr, `=================说明=====================`)
	fmt.Fprintln(os.Stderr, `webhook version: webhook/1.0.0`)
	fmt.Fprintln(os.Stderr, `使用方法: webhook [-h] [-wd] [-port]`)
	fmt.Fprintln(os.Stderr, `参数说明: `)
	flag.PrintDefaults()
	fmt.Fprintln(os.Stderr, `========================================`)
}


func main() {
	// nohup ./webhook -wd=/opt/docker-env/webhook > run.log &
	flag.Parse()
	fmt.Println("webhook 启动中...")
	http.HandleFunc("/delivery", Delivery)
	//设置 未路由页面匹配的方法
	http.HandleFunc("/", WebRoot)

	addr := *ip+ ":" +strconv.Itoa(*port)
	server := http.Server{
		Addr: addr,
		ReadTimeout: 60 * time.Second,
		WriteTimeout: 60 * time.Second,
	}
	fmt.Println("地址: "+ addr )
	fmt.Println("推送路由地址 : /delivery")
	fmt.Println("工作目录 :" + *wd)
	fmt.Println("进程ID: ", os.Getpid())
	fmt.Println("webhook 启动完成")
	server.ListenAndServe()
}

func WebRoot(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, `好巧哦，在这里遇见你，交个朋友吧！`)
}

func Delivery(w http.ResponseWriter, r *http.Request) {


	printLine("请求来也["+time.Now().String()+"]")
	if string(r.Method) != "POST" {
		printLine("忽略非POST请求")
		fmt.Fprintln(w, `OK`)
		return
	}
	event  := r.Header.Get("X-Gogs-Event")
	printBeforWithSpaceLine("请求事件:"+ event)
	signature  := r.Header.Get("X-Gogs-Signature")
	printBeforWithSpaceLine("请求signature:"+ signature)

	var bodySlc = make([]byte, 1024 * 4)
	bodyLen,readErr := r.Body.Read(bodySlc)

	if readErr == nil {
		fmt.Println("read body is nil")
	} else {
		printBeforWithSpaceLine("the body has ",bodyLen," bytes")
		switch strings.ToUpper(event) {
			case "PUSH":
				//异步执行
				go events.Push(bodySlc, bodyLen, signature, *wd)
			case "RELEASE":
				go events.Release(bodySlc, bodyLen)
			default:
				printBeforWithSpaceLine("未知事件推送 body 内容如下:")
				printBeforWithSpaceLine(string(bodySlc[:bodyLen]))
		}
	}
	//fmt.Println(projectName);
	//jsonStringBody := string(bodySlc)
	//fmt.Println("the body is:", jsonStringBody)

	fmt.Fprintln(w, `OK`)
}



func printLine(title string)  {
	printBeforWithSpaceLine(`-----------------------`+ title +`----------------------------`)
}


func printBeforWithSpaceLine(a ...interface{}) {
	fmt.Println(``)
	fmt.Println(a)
}
